package edu.mtu.citizenscience.mushroommapper.activity.main.find;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import edu.mtu.citizenscience.cs.utils.Message;
import edu.mtu.citizenscience.cs.utils.NewFeatureSupport;
import edu.mtu.citizenscience.cs.utils.Utils;
import edu.mtu.citizenscience.mushroommapper.MMActivity;
import edu.mtu.citizenscience.mushroommapper.activity.R;
import edu.mtu.citizenscience.mushroommapper.activity.main.FindActivity;
import edu.mtu.citizenscience.mushroommapper.model.report.ModelImage;
import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
/**
 * @author Corbin Uselton <corbinu@cwuselto@mtu.edu>
 * @copyright (c) 2012 MichiganTech <http://www.mtu.edu>
 * @since 1.0
 * 
 * Photo Activity Responsible taking, viewing and deleting find photos
 */
public class PhotoActivity extends MMActivity {
	// reference var for passing the activity result type
	public static final String RESULT_TYPE = "RESULT_TYPE";
	// reference var for passing the activity photo num
	public static final String PHOTO_NUM = "PHOTO_NUM";
	
	// reference vars for photo nums for the photo activity
	public static final int PHOTO_ONE = 1;
	public static final int PHOTO_TWO = 2;
	public static final int PHOTO_THREE = 3;
	
	// reference vars for photo take activity
	private static final int ACTION_TAKE_PHOTO = 1;
	
	// model for the image the photo activity is managing
	private ModelImage image;
	// the photo number
	private int num;
	
	/**
	 * Photo Activity creation handler
	 * 
	 * @param   savedInstanceState - Bundle - Bundle with launch info
	 * @return	void
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.photo_activity);
		
		// get the photo number from the launch intent
		this.num = this.getIntent().getExtras().getInt(PHOTO_NUM, -1);
		
		// check if have the photo number
		if (this.num == -1)
		{
			// don't have a photo number so end the activity
			this.finish();
		}
		
		// switch over the requested result type
		switch (this.getIntent().getExtras().getInt(RESULT_TYPE))
		{
			case FindActivity.RESULT_TYPE_IMAGE_GET:
				// get a new image for the report
				this.getImage();
			break;
			case FindActivity.RESULT_TYPE_IMAGE_DELETE:
				// are showing and possibly deleting an existing image so get the image id
				long imageId = this.getIntent().getLongExtra(ModelImage.IMAGE_ID, -1);
				
				// check to make sure have the image id
				if (imageId > -1)
				{
					// find the image model for the passed image id
					this.image = new ModelImage(this, imageId).find();
					
					// get the display size for the current android device
					Point displaySize = NewFeatureSupport.getDisplaySize(this.getWindowManager().getDefaultDisplay());
					
					// set the image preview to the image with the width of the display
					this.aq.id(R.id.imagePreview).image(this.image.getPath(), true, true, displaySize.x, 0).visible();
					
					// set the delete button text to the delete label
					this.aq.id(R.id.deleteImageButton).text(R.string.delete_button_label);
				}
				else
				{
					// don't have an image id so simply close the activity
					this.finish();
				}
			break;
			default:
				// don't have an accepted result type so simply close the activity
				this.finish();
			break;
		}
		
		// set the delete button clicked to removeImage
		aq.id(R.id.deleteImageButton).clicked(this, "removeImage");
	}
	
	/**
	 * Photo Activity activity result handler
	 * is called when a response is received from a 
	 * take photo intent launched from this activity
	 * 
	 * @param   requestCode - int - The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
	 * @param	resultCode - int - The integer result code returned by the child activity through its setResult().
	 * @param	data  - Intent - An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
	 * @return	void
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		// check to see if the take photo task was successful
		if (resultCode == RESULT_OK) 
		{
			// got the new image from the image take intent so put the id of the new image result and photo num in the return intent
			// send result as ok
			this.setResult(RESULT_OK, new Intent().putExtra(PHOTO_NUM, this.num).putExtra(ModelImage.IMAGE_ID, this.image.getId()));
			// close the activity
			this.finish();
		}
		else
		{
			// did not take photo so remove the tmp image file and the image model
			this.removeImage();
		}
	}
	
	/**
	 * Get a new image for the report by creating a 
	 * new image model and file and then launching an
	 * intent for image capture
	 * 
	 * @param   void
	 * @return	void
	 */
	public void getImage()
	{
		// check to make sure the device has a application to take images
		if (Utils.isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE))
		{
			// check to make sure the device has writable external storage to store the photo on
			if (Utils.isExternalStorageWritable())
			{
				// get a new dir for storing mushroom mapper photos inside the standard CitSci files location
				File photoDir = new File(Utils.citsciFiles(this), "mushroommapper/photo/");
				// make sure the photo dir and its parent dirs exist
				photoDir.mkdirs();
				
				try 
				{
					// create a new tmp jpg file in the photo dir with the current date time
					File imageFile = File.createTempFile(new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()), ".jpg", photoDir);
					
					// create a new image model to store the image information in the DB
					this.image = new ModelImage(this);
					// set the image model path to the new image file
					this.image.setPath(imageFile.getAbsolutePath());
					// set the image model date to the current date time
					this.image.setDate(Calendar.getInstance().getTime());
					// save the image model to the DB
					this.image.save();
					
					// create a new image capture intnet and put the tmp file as the photo output and launch new activity for take photo result
					this.startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile)), ACTION_TAKE_PHOTO);
				} 
				catch (IOException e) 
				{
					Message.showMessage(this, "Error: Could not create file to save photo to");
				}
			}
			else
			{
				Message.showMessage(this, "Error: External storage is no writable");
			}
		}
		else
		{
			Message.showMessage(this, "Error: No application installed capable of taking pictures");
		}
	}
	
	/**
	 * Remove the current image form the file system and db
	 * 
	 * @param   void
	 * @return	void
	 */
	public void removeImage()
	{
		// delete the image file
		this.image.getFile().delete();
		// delete the image model
		this.image.delete();
		
		// set result as ok and pass the photo num
		this.setResult(RESULT_OK, new Intent().putExtra(PHOTO_NUM, this.num));
		// close the activity
		this.finish();
	}

}
